/**
 * 路由管理
 * vue-router4 https://router.vuejs.org/
 */
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { useUserStore } from "@/stores/user";
import Main from "@/views/layout/Main.vue";
import Home from "@/views/Home.vue";
import Login from "@/views/Login.vue";
import Todos from "@/views/Todos.vue";
import TodoList from "@/views/TodoList.vue";
import TodoEdit from "@/views/TodoEdit.vue";

const routes: RouteRecordRaw[] = [
  {
    path: "/",
    component: Main,
    redirect: "/home",
    children: [
      {
        name: "home",
        path: "/home",
        component: Home,
      },
      {
        name: "login",
        path: "login",
        component: Login,
      },
      {
        name: "todos",
        path: "todos",
        component: Todos,
        redirect: "/todos/list",
        children: [
          {
            name: "todos.list",
            path: "list",
            component: TodoList,
          },
          {
            name: "todos.edit",
            path: "edit",
            component: TodoEdit,
          },
          {
            name: "todos.new",
            path: "new",
            component: TodoEdit,
          },
        ],
      },
      {
        name: "about",
        path: "about",
        component: () => import("@/views/About.vue"),
      },
    ],
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

// Global Before Guards
router.beforeEach(async (to, _, next) => {
  const userStore = useUserStore();
  // 如果待办页，则需要用户登录。
  if ((to.name as string).startsWith("todos") && !userStore.isAuth) {
    await userStore.getUserInfo();
    if (!userStore.isAuth) return next({ name: "login" });
  }
  next();
});

export default router;
